import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import MapView from '@arcgis/core/views/MapView'
import Map from '@arcgis/core/Map'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer'
import Graphic from '@arcgis/core/Graphic'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel'
import Query from '@arcgis/core/rest/support/Query'

let selectedFeature: Graphic | null = null

// 地块操作状态
export const operationState = reactive({
  isDrawing: false,
  isEditing: false,
  showAttributePanel: false,
  operationType: '' as 'add' | 'edit' | 'delete' | 'query' | '',
})

// 地块属性表单
// 地块属性表单
export const landParcelForm = reactive({
  FID: null as number | null,
  LandID: '',
  landType: '',
  Area: 0,
  landUse: '',
  OldUseType: [] as string[], // 新增字段，用于记录土地用途变更历史
  ownershipType: '',
  rightHolder: '',
  expirationDate: '',
  acquisitionDate: '',
  updateDate: '',
  parcelStatus: '',
  parcelGrade: '',
  remarks: '',
})

// 重置表单
export const resetForm = () => {
  landParcelForm.FID = null
  landParcelForm.LandID = ''
  landParcelForm.landType = ''
  landParcelForm.Area = 0
  landParcelForm.landUse = ''
  landParcelForm.OldUseType = [] // 重置土地用途变更历史
  landParcelForm.ownershipType = ''
  landParcelForm.rightHolder = ''
  landParcelForm.expirationDate = ''
  landParcelForm.acquisitionDate = ''
  landParcelForm.updateDate = ''
  landParcelForm.parcelStatus = ''
  landParcelForm.parcelGrade = ''
  landParcelForm.remarks = ''
}

// 地块类型选项
export const landTypeOptions = [
  { label: '耕地', value: '耕地' },
  { label: '林地', value: '林地' },
  { label: '草地', value: '草地' },
  { label: '住宅用地', value: '住宅用地' },
  { label: '商业用地', value: '商业用地' },
  { label: '工业用地', value: '工业用地' },
  { label: '交通用地', value: '交通用地' },
  { label: '水域', value: '水域' },
  { label: '其他', value: '其他' },
]

// 地块操作类
export function useLandParcelOperations(mapView: MapView | null, map: Map | null) {
  // 图形图层和草图模型
  let graphicsLayer: GraphicsLayer | null = null
  let sketchViewModel: SketchViewModel | null = null
  let landParcelLayer: FeatureLayer | null = null

  // 初始化地块操作
  const initLandParcelOperations = () => {
    if (!mapView || !map) return

    // 获取地块图层
    landParcelLayer = map.findLayerById('landParcelLayer') as FeatureLayer
    if (!landParcelLayer) {
      console.error('找不到地块图层')
      return
    }

    // 创建或获取图形图层
    graphicsLayer = map.findLayerById('editGraphicsLayer') as GraphicsLayer
    if (!graphicsLayer) {
      graphicsLayer = new GraphicsLayer({
        id: 'editGraphicsLayer',
        title: '编辑图层',
      })
      map.add(graphicsLayer)
    }

    // 创建草图视图模型
    sketchViewModel = new SketchViewModel({
      view: mapView,
      layer: graphicsLayer,
      defaultCreateOptions: {
        mode: 'hybrid',
      },
      defaultUpdateOptions: {
        toggleToolOnClick: false,
      },
    })

    // 监听草图创建完成事件
    sketchViewModel.on('create', (event) => {
      if (event.state === 'complete') {
        // 如果是添加操作，显示属性面板
        if (operationState.operationType === 'add') {
          const graphic = event.graphic
          // 计算面积（平方米）
          operationState.showAttributePanel = true
          operationState.isDrawing = false
        }
      }
    })

    // 监听点击事件，用于查询地块信息
    mapView.on('click', async (event) => {
      // 如果正在绘制，不执行查询
      if (operationState.isDrawing) return

      // 转换空间参考
      const mapPoint = event.mapPoint
      // 创建查询对象
      const query = new Query()
      query.geometry = mapPoint
      query.distance = 10 // 增加点击容差
      query.units = 'meters'
      query.spatialRelationship = 'intersects'
      query.returnGeometry = true
      query.outFields = ['*']

      try {
        // 查询地块图层
        if (landParcelLayer && landParcelLayer.visible) {
          // 强制刷新图层
          landParcelLayer.refresh()
          const result = await landParcelLayer.queryFeatures(query)

          if (result.features.length > 0) {
            const feature = result.features[0]
            selectedFeature = feature

            // 填充表单数据
            const attributes = feature.attributes
            landParcelForm.FID = attributes.FID
            landParcelForm.LandID = attributes.LandID || ''
            landParcelForm.landType = attributes.landType || ''
            landParcelForm.Area = attributes.Shape__Area || 0
            landParcelForm.landUse = attributes.landUse || ''
            landParcelForm.OldUseType = attributes.OldUseType
              ? JSON.parse(attributes.OldUseType)
              : []
            landParcelForm.ownershipType = attributes.ownershipType || ''
            landParcelForm.rightHolder = attributes.rightHolder || ''
            landParcelForm.expirationDate = attributes.expirationDate || ''
            landParcelForm.acquisitionDate = attributes.acquisitionDate || ''
            landParcelForm.updateDate = attributes.updateDate || ''
            landParcelForm.parcelStatus = attributes.parcelStatus || ''
            landParcelForm.parcelGrade = attributes.parcelGrade || ''
            landParcelForm.remarks = attributes.remarks || ''

            // 显示属性面板
            operationState.showAttributePanel = true
            operationState.operationType = 'query'
          } else {
            // 如果没有选中要素，隐藏属性面板
            selectedFeature = null
            operationState.showAttributePanel = false
          }
        }
      } catch (error) {
        console.error('查询地块失败:', error)
        ElMessage.error('查询地块失败')
      }
    })
  }

  // 开始绘制新地块
  const startDrawLandParcel = () => {
    if (!sketchViewModel) return

    // 清空图形图层
    if (graphicsLayer) {
      graphicsLayer.removeAll()
    }

    // 重置表单
    resetForm()

    // 设置状态
    operationState.isDrawing = true
    operationState.operationType = 'add'
    operationState.showAttributePanel = false

    // 开始绘制多边形
    sketchViewModel.create('polygon')

    ElMessage.info('请在地图上绘制地块范围')
  }

  // 取消绘制
  const cancelDraw = () => {
    if (!sketchViewModel) return

    sketchViewModel.cancel()
    operationState.isDrawing = false
    operationState.operationType = ''

    // 清空图形图层
    if (graphicsLayer) {
      graphicsLayer.removeAll()
    }
  }

  // 提交新增地块
  const submitAddLandParcel = async () => {
    if (!graphicsLayer || !landParcelLayer) return

    try {
      // 获取绘制的图形
      const graphics = graphicsLayer.graphics.toArray()
      if (graphics.length === 0) {
        ElMessage.warning('请先绘制地块范围')
        return
      }

      // 创建要素
      const graphic = graphics[0].clone()

      // 设置属性
      graphic.attributes = {
        LandID: landParcelForm.LandID,
        landType: landParcelForm.landType,
        landUse: landParcelForm.landUse,
        OldUseType: JSON.stringify(landParcelForm.OldUseType), // 将数组转为JSON字符串存储
        ownershipType: landParcelForm.ownershipType,
        rightHolder: landParcelForm.rightHolder,
        expirationDate: landParcelForm.expirationDate,
        acquisitionDate: landParcelForm.acquisitionDate,
        updateDate: landParcelForm.updateDate,
        parcelStatus: landParcelForm.parcelStatus,
        parcelGrade: landParcelForm.parcelGrade,
        remarks: landParcelForm.remarks,
      }

      // 添加要素
      const result = await landParcelLayer.applyEdits({
        addFeatures: [graphic],
      })

      if (result.addFeatureResults.length > 0) {
        ElMessage.success('添加地块成功')
        // 清空图形图层
        graphicsLayer.removeAll()
        // 重置状态
        operationState.isDrawing = false
        operationState.operationType = ''
        operationState.showAttributePanel = false
        // 刷新图层
        landParcelLayer.refresh()
      } else {
        ElMessage.error('添加地块失败')
      }
    } catch (error) {
      console.error('添加地块失败:', error)
      ElMessage.error('添加地块失败')
    }
  }

  // 开始修改地块
  const startEditLandParcel = () => {
    if (!selectedFeature) {
      ElMessage.warning('请先选择要修改的地块')
      return
    }

    operationState.operationType = 'edit'
  }

  // 提交修改地块
  const submitEditLandParcel = async () => {
    if (!landParcelLayer || !selectedFeature) return

    try {
      // 克隆选中的要素
      const feature = selectedFeature.clone()

      // 获取当前地块的原始土地用途
      const currentLandUse = selectedFeature.attributes.landUse

      // 如果土地用途发生变化，则将旧的用途添加到历史记录中
      const oldUseTypeArray = landParcelForm.OldUseType || []
      if (currentLandUse && currentLandUse !== landParcelForm.landUse) {
        // 确保不重复添加相同的用途
        if (!oldUseTypeArray.includes(currentLandUse)) {
          oldUseTypeArray.push(currentLandUse)
        }
      }

      // 更新属性
      feature.attributes = {
        ...feature.attributes,
        LandID: landParcelForm.LandID,
        landType: landParcelForm.landType,
        landUse: landParcelForm.landUse,
        OldUseType: JSON.stringify(oldUseTypeArray), // 更新土地用途变更历史
        ownershipType: landParcelForm.ownershipType,
        rightHolder: landParcelForm.rightHolder,
        expirationDate: landParcelForm.expirationDate,
        acquisitionDate: landParcelForm.acquisitionDate,
        updateDate: landParcelForm.updateDate,
        parcelStatus: landParcelForm.parcelStatus,
        parcelGrade: landParcelForm.parcelGrade,
        remarks: landParcelForm.remarks,
      }

      // 应用编辑
      const result = await landParcelLayer.applyEdits({
        updateFeatures: [feature],
      })

      if (result.updateFeatureResults.length > 0) {
        ElMessage.success('修改地块成功')
        // 重置状态
        operationState.operationType = ''
        operationState.showAttributePanel = false
        selectedFeature = null
        // 刷新图层
        landParcelLayer.refresh()
      } else {
        ElMessage.error('修改地块失败')
      }
    } catch (error) {
      console.error('修改地块失败:', error)
      ElMessage.error('修改地块失败')
    }
  }

  // 删除地块
  const deleteLandParcel = async () => {
    if (!landParcelLayer || !selectedFeature) {
      ElMessage.warning('请先选择要删除的地块')
      return
    }

    try {
      // 确认删除
      await ElMessageBox.confirm('确定要删除该地块吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })

      // 获取要素的 FID
      const FID = selectedFeature.attributes.FID

      // 应用删除
      const result = await landParcelLayer.applyEdits({
        deleteFeatures: [{ FID }],
      })

      if (result.deleteFeatureResults.length > 0) {
        ElMessage.success('删除地块成功')
        // 重置状态
        operationState.operationType = ''
        operationState.showAttributePanel = false
        selectedFeature = null
        // 刷新图层
        landParcelLayer.refresh()
      } else {
        ElMessage.error('删除地块失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除地块失败:', error)
        ElMessage.error('删除地块失败')
      }
    }
  }

  // 关闭属性面板
  const closeAttributePanel = () => {
    operationState.showAttributePanel = false
    operationState.operationType = ''
    selectedFeature = null

    // 清空图形图层
    if (graphicsLayer) {
      graphicsLayer.removeAll()
    }
  }

  return {
    initLandParcelOperations,
    startDrawLandParcel,
    cancelDraw,
    submitAddLandParcel,
    startEditLandParcel,
    submitEditLandParcel,
    deleteLandParcel,
    closeAttributePanel,
  }
}
